package com.demo.mykotlin.activity

import android.os.Bundle
import android.util.Log
import android.view.View
import androidx.recyclerview.widget.LinearLayoutManager
import com.demo.mykotlin.R
import com.demo.mykotlin.adapter.MsgAdapter
import com.demo.mykotlin.bean.MsgBean
import kotlinx.android.synthetic.main.activity_chat.*

/**
 * 聊天界面
 */
class ChatActivity : BaseActivity(), View.OnClickListener {
    private val msgList = ArrayList<MsgBean>()

    //延迟初始化lateinit var 允许不初始化，需要在使用前初始化
    private lateinit var adapter: MsgAdapter

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_chat)
        Log.d("TAG", "ChatActivity->onCreate()")
        initMSg()
        val layoutManager = LinearLayoutManager(this)

        adapter = MsgAdapter(msgList)
        recycleView.layoutManager = layoutManager
        recycleView.adapter = adapter

        send.setOnClickListener(this)
    }

    private fun initMSg() {
        val msgBean1 = MsgBean("你好 gjd。", MsgBean.TYPE_RECEIVES)
        msgList.add(msgBean1)
        Log.d("TAG", "ChatActivity->initMSg()")
    }

    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.send -> {
                val content = inputText.text.toString()
                if (content.isNotEmpty()) {
                    val msg = MsgBean(content, MsgBean.TYPE_SENT)
                    msgList.add(msg)
                    adapter.notifyItemInserted(msgList.size - 1)
                    recycleView.scrollToPosition(msgList.size - 1)
                    inputText.setText("")
                }
            }
        }
    }
}
